import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'  // 修改为直接导入Pinia的user store
import router from '@/router'

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API || '/api', // 修改为Vite的环境变量格式
    timeout: 100000
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        const userStore = useUserStore()
        const token = userStore.token
        if (token) {
            console.log('当前Token:', token)  // 调试用
            config.headers.Authorization = `Bearer ${token}`
        } else {
            console.warn('未找到有效Token')  // 调试用
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data

        if (res.code !== 200 && res.code !== 0) {
            const errorMessage = res.message || '请求失败，请稍后重试'
            ElMessage({
                message: errorMessage,
                type: 'error',
                duration: 5 * 1000
            })

            // 仅处理非401的权限错误，401交给错误拦截器统一处理
            if (res.code === 403) {
                const userStore = useUserStore()
                userStore.showAuthModal = true
            }
            return Promise.reject(new Error(errorMessage))
        }
        return res
    },
    async error => {
        console.log('Response Error:', error)

        const originalRequest = error.config

        // 统一处理401错误（包括token刷新）
        if (error.response?.status === 401) {
            const userStore = useUserStore()

            // 不是刷新token请求且未重试过
            if (!originalRequest._retry &&
                originalRequest.url !== '/public/user/refresh_token') {
                originalRequest._retry = true

                try {
                    const refreshToken = sessionStorage.getItem('refreshToken')
                    if (!refreshToken) throw new Error('无有效refreshToken')

                    const { data } = await service({
                        url: '/public/user/refresh_token',
                        method: 'post',
                        data: { refreshToken }
                    })
                    if (data.code != 200) {
                        throw new Error('刷新token失败')
                    }
                    userStore.setToken(data.token)
                    originalRequest.headers['Authorization'] = 'Bearer ' + data.token
                    return service(originalRequest)

                } catch (refreshError) {
                    userStore.clearAuth()
                    userStore.showAuthModal = true
                    router.push('/')
                    return Promise.reject(refreshError)
                }
            } else {
                // 刷新失败或其他401情况
                userStore.showAuthModal = true
            }
        }

        let errorMessage = '请求失败，请稍后重试'
        if (error.response) {
            errorMessage = error.response.data?.message ||
                error.response.statusText ||
                errorMessage

            switch (error.response.status) {
                case 400: error.message = errorMessage; break
                case 401:
                    error.message = errorMessage
                    const userStore = useUserStore()
                    userStore.showAuthModal = true
                    break
                case 403:
                    error.message = '拒绝访问'
                    break
                case 404:
                    error.message = `请求地址出错: ${error.response.config.url}`
                    break
                case 408:
                    error.message = '请求超时'
                    break
                case 500:
                    error.message = '服务器内部错误'
                    break
                case 501:
                    error.message = '服务未实现'
                    break
                case 502:
                    error.message = '网关错误'
                    break
                case 503:
                    error.message = '服务不可用'
                    break
                case 504:
                    error.message = '网关超时'
                    break
                case 505:
                    error.message = 'HTTP版本不受支持'
                    break
                default:
                    error.message = `连接错误: ${error.message}`
            }
        }

        ElMessage({
            message: error.message || errorMessage,
            type: 'error',
            duration: 5 * 1000
        })

        return Promise.reject(error)
    }
)

export default service